package cn.tp.ksoft.civil_driver.module.order.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.List;

import cn.tp.ksoft.civil_driver.R;
import cn.tp.ksoft.civil_driver.bean.OrderBean;
import cn.tp.ksoft.civil_driver.bean.OrderDetailBean;
import cn.tp.ksoft.civil_driver.bean.ResultBean;
import cn.tp.ksoft.civil_driver.module.order.OrderConfirmActivity;
import cn.tp.ksoft.civil_driver.module.order.RefuseOrderActivity;
import cn.tp.ksoft.civil_driver.request.DriverOrderRequest;
import cn.tp.ksoft.civil_driver.request.RequestModules;
import cn.tp.ksoft.civil_driver.utils.Constants;
import cn.tp.ksoft.civil_driver.utils.TimestampTypeAdapter;
import cn.tp.ksoft.civil_driver.view.simple.SpaceItemDecoration;
import cn.tp.ksoft.library_civil.utils.DateUtil;
import cn.tp.ksoft.library_civil.utils.StringUtils;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * Created by zhusong on 16/5/6.
 */
public class BaseOrderFragment extends Fragment implements RequestModules {
    protected int typeId;
    private final int PAGE_SIZE = 20;
    public int getTypeId() {
        return typeId;
    }
    protected SparseArray<OrderBean> mData = new SparseArray<>();
//    protected SparseArray<Long> mOrderIdIndex = new SparseArray<>();

    protected PtrClassicFrameLayout mPtrFrame;
    protected boolean isLoadingMore;
    protected RecyclerView mRv;
    private OrderAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
	static Gson gson;
    protected DriverOrderRequest request;

//    private final int REQUEST_RECEIPT = 1;
    private final int REQUEST_REFUSE = 2;
    private final int REQUEST_CONFIRM_DURATION = 3;
    public BaseOrderFragment() {
    }

    public static BaseOrderFragment newInstance(int typeId) {
        BaseOrderFragment fragment = new BaseOrderFragment();
        fragment.typeId = typeId;
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.driver_order_page_item, container, false);
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser
                && null != mPtrFrame
                && !mPtrFrame.isRefreshing()) {
            mPtrFrame.autoRefresh(true);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mPtrFrame = (PtrClassicFrameLayout) view;
        mRv = (RecyclerView) view.findViewById(R.id.rv);
        mAdapter = new OrderAdapter();
        mLayoutManager = new LinearLayoutManager(getContext());
        mRv.setLayoutManager(mLayoutManager);
        mRv.setAdapter(mAdapter);
        int itemSpace = Math.round(getResources().getDisplayMetrics().density * 10);
        mRv.addItemDecoration(new SpaceItemDecoration(itemSpace));
        mPtrFrame.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                request.getLastestFlightOrder(getTypeId());
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return super.checkCanDoRefresh(frame, mRv, header);
            }
        });
        mRv.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
                int totalItemCount = mLayoutManager.getItemCount();
                //lastVisibleItem >= totalItemCount - 4 表示剩下4个item自动加载，各位自由选择
                // dy>0 表示向下滑动
                if (lastVisibleItem >= totalItemCount - 1 && dy > 0 && !isLoadingMore) {
                    isLoadingMore = true;
                    loadMore();
                }
            }
        });
		GsonBuilder gsonBuilder = new GsonBuilder();
		gsonBuilder.registerTypeAdapter(Date.class, new TimestampTypeAdapter());
		gson = gsonBuilder.create();
		//↑
        request = new DriverOrderRequest(getContext(), new OrdersHandler(this));
        if (getUserVisibleHint()) {
            mPtrFrame.autoRefresh(true);
        }
    }

    protected void loadMore() {
        if (null == mData || mData.size() == 0) {
            return;
        }
        OrderBean oldesetOrder = mData.valueAt(mData.size() - 1);
        request.list(oldesetOrder.getOrderTime().getTime(), PAGE_SIZE, getTypeId());
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_REFUSE) {

        }
    }

    class OrderHolder extends RecyclerView.ViewHolder {
//        ImageView mIconIv;
//        TextView mNameTv;
        TextView mStatusTv;
        TextView mStartTimeTv;
        TextView mAddressTv;
//        TextView mPriceTv;
        Button mRefuseBtn;
        Button mDeleteBtn;
        Button mReceiptBtn;
        Button mFinishBtn;

        public OrderHolder(View itemView) {
            super(itemView);
//            mIconIv = (ImageView) itemView.findViewById(R.id.iv_icon);
//            mNameTv = (TextView) itemView.findViewById(R.id.tv_name);
            mStatusTv = (TextView) itemView.findViewById(R.id.tv_status);
            mStartTimeTv = (TextView) itemView.findViewById(R.id.tv_start_time);
            mAddressTv = (TextView) itemView.findViewById(R.id.tv_address);
//            mPriceTv = (TextView) itemView.findViewById(R.id.tv_price);
            mRefuseBtn = (Button) itemView.findViewById(R.id.btn_refuse);
            mDeleteBtn = (Button) itemView.findViewById(R.id.btn_delete);
            mReceiptBtn = (Button) itemView.findViewById(R.id.btn_receipt);
            mFinishBtn = (Button) itemView.findViewById(R.id.btn_finish);
        }

        public void updateOrder(final OrderBean orderBean) {
            int status = orderBean.getStatus();
            final Long orderId = orderBean.getId();
            if (status == Constants.ORDER_STATUS_WAIT) {
                mStatusTv.setText(getString(R.string.driver_order_status_wait));
                mDeleteBtn.setVisibility(View.GONE);
                mFinishBtn.setVisibility(View.GONE);
                mReceiptBtn.setVisibility(View.VISIBLE);
                mRefuseBtn.setVisibility(View.VISIBLE);
                mReceiptBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        request.confirmOrder(orderId);
                    }
                });
                mRefuseBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), RefuseOrderActivity.class);
                        intent.putExtra(Constants.KEY_ORDER_ID, orderId);
                        startActivityForResult(intent, REQUEST_REFUSE);
                    }
                });

            } else if (status == Constants.ORDER_STATUS_RECEIPT) {
                mStatusTv.setText(getString(R.string.driver_order_status_receipt));
                mDeleteBtn.setVisibility(View.GONE);
                mFinishBtn.setVisibility(View.VISIBLE);
                mReceiptBtn.setVisibility(View.GONE);
                mRefuseBtn.setVisibility(View.GONE);
                mFinishBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), OrderConfirmActivity.class);
                        intent.putExtra(Constants.KEY_ORDER_BEAN, orderBean);
                        startActivityForResult(intent, REQUEST_CONFIRM_DURATION);
                    }
                });
            } else if (status == Constants.ORDER_STATUS_FINISH) {
                mStatusTv.setText(getString(R.string.driver_order_status_finish));
                mDeleteBtn.setVisibility(View.VISIBLE);
                mFinishBtn.setVisibility(View.GONE);
                mReceiptBtn.setVisibility(View.GONE);
                mRefuseBtn.setVisibility(View.GONE);
                mDeleteBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        request.deleteOrder(orderId);
                    }
                });
            } else if (status == Constants.ORDER_STATUS_CLOSE) {
                mStatusTv.setText(getString(R.string.driver_order_status_close));
                mDeleteBtn.setVisibility(View.VISIBLE);
                mFinishBtn.setVisibility(View.GONE);
                mReceiptBtn.setVisibility(View.GONE);
                mRefuseBtn.setVisibility(View.GONE);
                mDeleteBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        request.deleteOrder(orderId);
                    }
                });
            }
        }
    }

    class OrderAdapter extends RecyclerView.Adapter<OrderHolder> {
        @Override
        public OrderHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.driver_my_order_item, viewGroup, false);
            return new OrderHolder(view);
        }

        @Override
        public void onBindViewHolder(OrderHolder holder, int position) {
            final OrderBean orderBean = mData.valueAt(position);
        	OrderDetailBean detailBean = gson.fromJson(orderBean.getDetail(),
    				OrderDetailBean.class);
        	
        	if(detailBean !=null){
    			holder.mAddressTv.setText(StringUtils.replaceNull(detailBean.getStartAddress()));
    			holder.mStartTimeTv.setText(DateUtil.D2Syrsf(detailBean.getBycarStartTime())+"出发|"+"包车"+DateUtil.hours2day(detailBean.getBycarLong()));
//    			holder.mNameTv.setText(StringUtils.replaceNull(orderBean.getContact()));
    			holder.updateOrder(orderBean);
    		}
        }

        @Override
        public int getItemCount() {
            return mData != null ? mData.size() : getTypeId();
        }
    }


    private static class OrdersHandler extends Handler {

        private WeakReference<BaseOrderFragment> mRef;

        public OrdersHandler(BaseOrderFragment fragment) {
            mRef = new WeakReference<BaseOrderFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            BaseOrderFragment fragment = mRef.get();
            if (null == fragment) {
                return;
            }

            if (msg.what == GETLASTESTFLIGHTORDER) {
                fragment.mPtrFrame.refreshComplete();
            } else if (msg.what == REQUEST_ORDER_LIST) {
                fragment.isLoadingMore = false;
            }


            ResultBean result = (ResultBean) msg.obj;
            if(null == result) {
                return;
            }

            if (!result.isSuccess()) {
                Toast.makeText(fragment.getActivity(), result.getTitle(),
                        Toast.LENGTH_SHORT).show();
                return;
            }
            switch (msg.what) {
                case GETLASTESTFLIGHTORDER : {
                    // update list
                    if (!StringUtils.isEmpty(result.getData())) {
                        List<OrderBean> list = gson.fromJson(gson.toJson(result.getData()),
                                new TypeToken<List<OrderBean>>() { }.getType());
                        fragment.updateList(list);
                    }
                    break;
                }

                case REQUEST_ORDER_LIST : {
                    // update list
                    if (!StringUtils.isEmpty(result.getData())) {
                        List<OrderBean> list = gson.fromJson(gson.toJson(result.getData()),
                                new TypeToken<List<OrderBean>>() { }.getType());
                        fragment.appendList(list);
                    }
                    break;
                }

                case REQUEST_ORDER_DELETE : {
                    Long orderId = (Long) result.getData();
                    fragment.removeOrderItem(orderId);
                    break;
                }

                case REQUEST_ORDER_FINISH : {
                    fragment.mPtrFrame.autoRefresh();
                    break;
                }

                case REQUEST_ORDER_COFIRM : {
                    fragment.mPtrFrame.autoRefresh();
                    break;
                }
            }
        }
    }

    private void addOrderItem(int index, OrderBean bean) {
        OrderDetailBean detailBean = gson.fromJson(bean.getDetail(),
                OrderDetailBean.class);
        bean.setDetailBean(detailBean);
        mData.append(index, bean);
    }

    private void removeOrderItem(Long orderId) {
        for (int i = 0, len = mData.size(); i < len; i++) {
            OrderBean bean = mData.valueAt(i);
            if(bean.getId().longValue() == orderId.longValue()) {
                int index = i;
                if (index >= 0) {
                    mData.removeAt(index);
                    mAdapter.notifyItemRemoved(index);
                }
                break;
            }
        }

    }

    //刷新数据
    private void updateList(List<OrderBean> list){
        int size = mData.size();
        mData.clear();
        mAdapter.notifyItemRangeRemoved(0, size);

        if (null == list) {
            return;
        }

        for (int i = 0, len = list.size(); i < len; i++) {
            addOrderItem(i, list.get(i));
        }

        size = mData.size();
        mAdapter.notifyItemRangeInserted(0, size);
    }
    
    // append data
    private void appendList(List<OrderBean> list){
        if (null == list) {
            return;
        }
        int size = mData.size();
        for (int i = 0, len = list.size(); i < len; i++) {
            addOrderItem(size + i, list.get(i));
        }
        mAdapter.notifyItemRangeInserted(size, list.size());
    }
}
